interface RequestOptions extends RequestInit {
  data?: any;
  isFormData?: boolean;  // 添加标识是否为表单数据
}

export async function request(url: string, options?: RequestOptions) {
  const defaultOptions = {
    credentials: 'include' as RequestCredentials,
    headers: {
      'Content-Type': 'application/json',
    },
  };

  const token = localStorage.getItem('token');
  if (token) {
    defaultOptions.headers = {
      ...defaultOptions.headers,
      'Authorization': token,
    };
  }

  const newOptions = { ...defaultOptions, ...options };
  
  // 处理 FormData 请求
  if (options?.isFormData) {
    delete newOptions.headers['Content-Type'];  // 让浏览器自动设置
  } else if (newOptions.data) {
    newOptions.body = JSON.stringify(newOptions.data);
    delete newOptions.data;
  }

  try {
    const response = await fetch(url, newOptions);
    
    if (response.status === 401) {
      localStorage.removeItem('token');
      window.location.href = '/login';
      throw new Error('登录已过期，请重新登录');
    }

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.detail || '请求失败');
    }

    return data;
  } catch (error) {
    if (error instanceof Error) {
      throw error;
    }
    throw new Error('网络请求失败');
  }
}

// 文件上传请求
export async function uploadFileRequest(url: string, file: File, data?: Record<string, any>) {
  const formData = new FormData();
  formData.append('file', file);
  
  if (data) {
    Object.entries(data).forEach(([key, value]) => {
      formData.append(key, value);
    });
  }

  return request(url, {
    method: 'POST',
    body: formData,
    isFormData: true
  });
}

